package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.HttpClient;
import com.changgou.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangyuhong
 * Date:2020/5/20
 */
@Service
public class WeixinPayServiceImpl implements WeixinPayService {
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.partner}")
    private String partner;
    @Value("${weixin.partnerkey}")
    private String partnerkey;
    @Value("${weixin.notifyurl}")
    private String notifyurl;

    @Override
    public Map createNative(Map<String, String> parameter) {
        try {
            //1、封装参数  请求支付连接必须的参数  https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
            HashMap param = new HashMap<>();
            param.put("appid", appid);                              //应用ID
            param.put("mch_id", partner);                           //商户ID号  商户账号
            param.put("nonce_str", WXPayUtil.generateNonceStr());   //随机数
            //签名不管 在进行转换成xml的时候直接添加签名
            param.put("body", "畅购");                                //订单描述

            param.put("out_trade_no", parameter.get("out_trade_no"));                 //商户订单号
            param.put("total_fee", parameter.get("total_fee"));                      //交易金额  单位是分

            param.put("spbill_create_ip", "127.0.0.1");           //终端IP
            param.put("notify_url", notifyurl);                    //回调地址
            param.put("trade_type", "NATIVE");                     //交易类型   NATIVE:表示扫描支付, 还有JSAPI ,APP 类型,官网上都有
            // 额外数据(到时候付款完后让微信返回的这样就知道是那个地方来的了
            param.put("attach", JSON.toJSONString(parameter));  //携带attach数据 吧{out_trade_no,total_fel,from:1}

            //2、将参数转成xml字符，并携带签名
            String signedXml = WXPayUtil.generateSignedXml(param, partnerkey);  //把参数转成xml的格式,因为2.0版本的支付宝只识别xml版本的数据 例如:<xml><appid>wx2421b1c4370ec43b</appid></xml>

            ///3、执行请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);  //设置以https方式请求  微信支付要求是http
            httpClient.setXmlParam(signedXml);  //设置数据,也就是
            httpClient.post();  //开始请求 post

            //4、获取参数
            String content = httpClient.getContent();
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);//回传的也是xml格式的  所以要转成map
            System.out.println("stringMap:" + stringMap);  //这个参数很多
            // {nonce_str=tDGlpwgpc6p9wNpP, code_url=weixin://wxpay/bizpayurl?pr=dAlOBg7,
            // appid=wx8397f8696b538317, sign=FA54BCEDFB936F1B2AD8FC5A14E60ACE, trade_type=NATIVE,
            // return_msg=OK, result_code=SUCCESS, mch_id=1473426802, return_code=SUCCESS,
            // prepay_id=wx20224632179431350e121f131283731700}

            //5、获取部分页面所需参数
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("code_url", stringMap.get("code_url"));  //二维码的收款地址
            dataMap.put("out_trade_no", parameter.get("out_trade_no"));  //订单id
            dataMap.put("total_fee", parameter.get("total_fee"));  //支付的钱
            return dataMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, String> queryPayStatus(String out_trade_no) {
        try {
            //1.封装参数
            Map param = new HashMap();
            param.put("appid", appid);                            //应用ID
            param.put("mch_id", partner);                         //商户号
            param.put("out_trade_no", out_trade_no);              //商户订单编号
            param.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符

            //2、将参数转成xml字符，并携带签名
            String paramXml = WXPayUtil.generateSignedXml(param, partnerkey);

            //3、发送请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //4、获取返回值，并将返回值转成Map
            String content = httpClient.getContent();
            return WXPayUtil.xmlToMap(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /***
     * 关闭支付
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> closePay(Long orderId) throws Exception {
        HashMap param = new HashMap<>();
        param.put("appid", appid);                              //应用ID
        param.put("mch_id", partner);                           //商户ID号  商户账号
        param.put("out_trade_no", orderId);                 //商户订单号
        param.put("nonce_str", WXPayUtil.generateNonceStr());   //随机数
        String xmlParam = WXPayUtil.mapToXml(param);
        //确定url
        String url = "https://api.mch.weixin.qq.com/pay/closeorder";

        //发送请求
        HttpClient httpClient = new HttpClient(url);
        //https
        httpClient.setHttps(true);
        //提交参数
        httpClient.setXmlParam(xmlParam);

        //提交
        httpClient.post();

        //获取返回数据
        String content = httpClient.getContent();

        //将返回数据解析成Map
        return  WXPayUtil.xmlToMap(content);
    }
}
